package com.huohuo.zkcurator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
public class NodeCacheListern {

    @PostConstruct
    public void p() throws Exception {
        //监听数据节点的变更，会触发事件
       final NodeCache nodeCache = new NodeCache(CuratorOpration.curatorFramework,"/super/test"  );
       nodeCache.start(true);
       //添加监听
       nodeCache.getListenable().addListener( new NodeCacheListener() {
           @Override
           public void nodeChanged() throws Exception {
               byte [] data = nodeCache.getCurrentData().getData();
               System.out.println("节点路径："+nodeCache.getCurrentData().getPath()
               +"节点数据："+new String( data ));
           }
       } );

    }


    /**
     * 监听子节点
     */
    @PostConstruct
    public void childredListener() throws Exception {
        final PathChildrenCache pathChildrenCache =
                new PathChildrenCache(CuratorOpration.curatorFramework,"/super/test",true);
        /**
         * StartMode.NORMAL:异步初始化
         * StartMode.POST_INITIALIZED_EVENT：异步初始化，初始化之后触发事件
         * StartMode.BUILD_INITIAL_CACHE：同步初始化
         */
        pathChildrenCache.start( PathChildrenCache.StartMode.POST_INITIALIZED_EVENT );
        //当前数据节点的子节点数据列表
        List<ChildData> childData = pathChildrenCache.getCurrentData();
        System.out.println(childData.toString());
        pathChildrenCache.getListenable().addListener( new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getData() != null){
                    String path = event.getData().getPath();
                if (event.getType().equals( PathChildrenCacheEvent.Type.INITIALIZED )){
                    System.out.println("子节点初始化.......");
                }else if (event.getType().equals( PathChildrenCacheEvent.Type.CHILD_ADDED )){
                    System.out.println(new String( "子节点路径："+path + ",添加子节点数据："+ new String(event.getData().getData() )));
                }else if (event.getType().equals( PathChildrenCacheEvent.Type.CHILD_UPDATED )){
                    System.out.println("子节点路径："+path+",数据更新"+ new String( event.getData().getData() ));
                }else if(event.getType().equals( PathChildrenCacheEvent.Type.CHILD_REMOVED )){
                    System.out.println("子节点路径："+path+",数据删除"+ new String( event.getData().getData() ));
                }
               }
            }

        } );

    }

}
